import { Component, OnInit } from '@angular/core';
import { LocalStorage } from '@core/local.storage';
import { ApiService } from '../../../core/api.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { forkJoin } from 'rxjs';
import { FormBuilder, FormControl } from '@angular/forms';
import { environment } from '../../../../environments/environment';
import { ActivatedRoute, Params } from '@angular/router';
import { _HttpClient } from '@delon/theme';
import { ReuseTabService } from '@delon/abc';

@Component({
    selector: 'app-zymgl',
    templateUrl: './zymgl.component.html',
    styleUrls: ['./zymgl.component.less'],
})

export class ZymglComponent implements OnInit {
    value = '';
    formgroup_query;
    formgroup_add;
    formgroup_edit;
    formgroup_detail;
    data = {
        tableTotal: 0,
        tableData: [],
        tablePagination: {
            page: 1,
            rows: 10
        }
    };
    lockHeadScroll = { y: window.innerHeight - 350 + 'px' };
    pic = {
        visible: false,
        title: '',
        picStyle: {
            width: '90%',
            height: '90%',
            margin: '5px auto'
        },
        panelStyle: {
            width: '600px'
        },
        src: '',
        hide() {
            this.visible = false;
        },
        show: (data) => {
            if (data.addrUrl) {
                this.pic.visible = true;
                this.pic.setUrl(data);
            }
        },
        setUrl: (data) => {
            if (data.addrUrl) {
                const pre = environment.apiBase + '/csmis/';
                let url = pre + data.addrUrl;
                if (url.indexOf(',') == url.length - 1) {
                    url = url.replace(/,$/, '');
                }
                this.pic.src = url;
            } else {
                this.pic.src = '';
            }
        }
    };

    queryData: any = {};
    editData: any = {};
    addData: any = {};
    detailData: any = {};
    ctrlNames = {
        nId: 'zymid',
        name: 'zymmc',
        dev: 'bhsb',
        station: 'cz',
    };

    ctrlNames_add = {
        name: 'zymmc_add',
        dev: 'bhsb_add',
        station: 'cz_add',
        doorkey: 'ysszd_add',
        addrUrl: 'jttdz_add',
    };

    ctrlNames_detail = {
        name: 'zymmc_detail',
        dev: 'bhsb_detail',
        // station: 'cz_detail',
        doorkey: 'ysszd_detail',
        addrUrl: 'jttdz_detail',
        stationTrans: 'stationName',
    };

    ctrlNames_edit = {
        nId: 'id_edit',
        name: 'zymmc_edit',
        dev: 'bhsb_edit',
        station: 'cz_edit',
        // stationTrans: 'czName_edit',
        doorkey: 'ysszd_edit',
        addrUrl: 'jttdz_edit',
    };


    addPanel = {
        showAdd: false,
        title: '新增作业门',
        loading: false,
        style: {
            width: '600px'
        }
    };
    detailPanel = {
        showdetail: false,
        title: '作业门详情',
        loading: false,
        style: {
            width: '600px'
        }
    };

    editPanel = {
        showEdit: false,
        title: '修改作业门',
        loading: false,
        style: {
            width: '600px'
        }
    };

    userInfo = JSON.parse(this.ls.get('loginInfo'));
    uploadAction: string;
    pageType: any;

    constructor(public ls: LocalStorage,
        private modalService: NzModalService,
        private apiService: ApiService,
        private message: NzMessageService,
        private formBuilder: FormBuilder,
        private http: _HttpClient,
        private activatedRoute: ActivatedRoute,
        private reuseTabService: ReuseTabService,
    ) { }


    ngOnInit() {
        this.initDatas();
        this.uploadAction = environment.apiBase + '/csmis/servlet/UploadHandleServlet';
        this.formgroup_query = this.formBuilder.group({});
        this.formgroup_add = this.formBuilder.group({});
        this.formgroup_edit = this.formBuilder.group({});
        this.formgroup_detail = this.formBuilder.group({});
        this._addControls(this.formgroup_query, this.ctrlNames);
        this._addControls(this.formgroup_add, this.ctrlNames_add);
        this._addControls(this.formgroup_edit, this.ctrlNames_edit);
        this._addControls(this.formgroup_detail, this.ctrlNames_detail);

        this.getStation(() => {
            this.query(true);
        });
        this.activatedRoute.params.subscribe((params: Params) => {
            this.pageType = params.status;
            if (params.status == 'edit') {
                this.reuseTabService.title = '作业门维护';
            }
            if (params.status == 'view') {
                this.reuseTabService.title = '作业门查看';
            }
        });

    }

    initDatas() {
        this.initQueryData();
        this.initEditData();
        this.initAddData();
        this.initDetailData();
    }
    initQueryData() {
        /**
        * 查询条件栏中的各控件需要的数据及逻辑
        */
        this.queryData = {
            station: {
                data: [],
                filterData: [],
                lastNode: null,
                lastValue: null,
                nowValue: null,
                nzTreeClick: (e) => {
                    this.queryData.station.lastNode = e.node;
                },
                onChange: (e) => {
                    let wrongSelect = false;
                    if (e && e.length) {
                        if (this.queryData.station.lastNode && !this.queryData.station.lastNode.isLeaf) {
                            this.message.create('error', '您选的是车间,请展开后选择车站');
                            wrongSelect = true;
                        }
                    }
                    if (wrongSelect) {
                        setTimeout(() => {
                            this.queryData.station.nowValue = this.queryData.station.lastValue;
                            wrongSelect = false;
                        }, 300);
                    } else {
                        this.queryData.station.lastValue = e;
                    }
                }
            },
            dev: {
                lastStationId: '',
                data: [],
                nowValues: [],
            }
        };
    }
    initEditData() {
        /**
         * 修改弹窗中的各控件需要的数据及逻辑
         */
        this.editData = {
            row: null,
            station: {
                data: [],
                filterData: [],
                lastNode: null,
                lastValue: null,
                nowValue: null,
                nzTreeClick: (e) => {
                    this.editData.station.lastNode = e.node;
                },
                onChange: (e) => {
                    let wrongSelect = false;
                    if (e && e.length) {
                        if (this.editData.station.lastNode && !this.editData.station.lastNode.isLeaf) {
                            this.message.create('error', '您选的是车间,请展开后选择车站');
                            wrongSelect = true;
                        }
                    }
                    if (wrongSelect) {
                        setTimeout(() => {
                            this.editData.station.nowValue = this.editData.station.lastValue;
                            wrongSelect = false;
                        }, 300);
                    } else {
                        this.editData.station.lastValue = e;
                    }
                }
            },
            dev: {
                lastStationId: '',
                station: {// 在打开edit弹窗时用于保存原数据内容,以进行ID和中文的翻译
                    id: '',
                    name: ''
                },
                lastNode: null,
                historyNodes: [],
                expandNodeKeys: [],
                lastValues: [],
                nowValues: [],
                data: [],
                treeNodes_real: [],
                doReturn: true,
                nzTreeClick: (e) => {
                    this.editData.dev.lastNode = e.node;
                    // this.editData.dev.historyNodes.push(e.node);
                    const hisNodes = this.editData.dev.historyNodes;
                    if (hisNodes.findIndex(el => el.key == e.node.key) == -1) {
                        this.editData.dev.historyNodes.push(e.node);
                    }
                    this.editData.dev.doReturn = false;
                },
                wrongSelect: false,
                onDevChange: (e) => {
                    if (this.editData.dev.doReturn) {
                        return;
                    }
                    let childKeys = [];
                    const wrongFunc = () => {
                        if (this.editData.dev.wrongSelect) {
                            setTimeout(() => {
                                this.editData.dev.doReturn = true;
                                this.editData.dev.nowValues = this.editData.dev.lastValues;
                                this.editData.dev.wrongSelect = false;
                            }, 300);
                        } else if (this.editData.dev.checkAll) {
                            this.editData.dev.doReturn = true;
                            this.editData.dev.nowValues = this.editData.dev.lastValues.concat(childKeys);
                            this.editData.dev.lastValues = this.editData.dev.nowValues;
                            this.editData.dev.checkAll = false;
                        } else {
                            this.editData.dev.lastValues = e;
                        }
                    };
                    if (e && e.length) {
                        // let nodes = this.treeSelect_add.selectedNodes;
                        if (this.editData.dev.lastNode.level == 0) {
                            this.message.create('error', '您选的是设备类型,请展开后选择设备');
                            this.editData.dev.wrongSelect = true;
                            wrongFunc();
                        } else if (this.editData.dev.lastNode.level == 1) {
                            this.editData.dev.checkAll = true;
                            this.modalService.confirm({
                                nzTitle: '操作确认',
                                nzContent: `您选的是设备类型,您需要 全选 该类型下的设备吗？（需要先展开该节点）`,
                                nzOkText: '确定',
                                nzCancelText: '取消',
                                nzOnOk: () => {
                                    const lastNode = this.editData.dev.lastNode;
                                    if (lastNode.isExpanded == false && lastNode.children && !lastNode.children.length) {
                                        this.message.warning(`请先展开该节点`);
                                        return;
                                    } else {
                                        childKeys = [];
                                        lastNode.children.forEach(childNode => {
                                            childKeys.push(childNode.key);
                                            const hisNodes = this.editData.dev.historyNodes;
                                            if (hisNodes.findIndex(el => el.key == childNode.key) == -1) {
                                                this.editData.dev.historyNodes.push(childNode);
                                            }
                                            // this.editData.dev.historyNodes.push(childNode);
                                        });
                                    }
                                    wrongFunc();
                                },
                                nzOnCancel: () => {
                                    this.editData.dev.wrongSelect = true;
                                    wrongFunc();
                                }
                            });
                        } else {
                            wrongFunc();
                        }
                    }

                }
                // onDevChange: (e) => {
                //     if (e && e.length) {
                //         if (this.editData.dev.lastNode && !this.editData.dev.lastNode.isLeaf) {
                //             this.message.create('error', '您选的是设备类型,请展开后选择设备');

                //             this.editData.dev.wrongSelect = true;
                //         }
                //         // else if (e.length > 2) {
                //         //     this.message.create('error', '最多只能选2个设备');
                //         //     this.editData.dev.wrongSelect = true;
                //         // }
                //     }
                //     if (this.editData.dev.wrongSelect) {
                //         setTimeout(() => {
                //             this.editData.dev.nowValues = this.editData.dev.lastValues;
                //             this.editData.dev.wrongSelect = false;
                //         }, 300);
                //     } else {
                //         this.editData.dev.lastValues = e;
                //     }
                // }
            },
            traficImg: (e) => {
                if (e && e.type === 'success') {
                    const url = e.file.response.download;
                    this.formgroup_edit.patchValue({
                        [this.ctrlNames_edit.addrUrl]: url,
                    });
                }
            },
        };
    }

    initAddData() {
        /**
         * 新增弹窗中的各控件需要的数据及逻辑
         */
        this.addData = {
            station: {
                data: [],
                filterData: [],
                lastNode: null,
                lastValue: null,
                nowValue: null,
                nzTreeClick: (e) => {
                    this.addData.station.lastNode = e.node;
                },
                onChange: (e) => {
                    let wrongSelect = false;
                    if (e && e.length) {
                        if (this.addData.station.lastNode && !this.addData.station.lastNode.isLeaf) {
                            this.message.create('error', '您选的是车间,请展开后选择车站');
                            wrongSelect = true;
                        }
                    }
                    if (wrongSelect) {
                        setTimeout(() => {
                            this.addData.station.nowValue = this.addData.station.lastValue;
                            wrongSelect = false;
                        }, 300);
                    } else {
                        this.addData.station.lastValue = e;
                    }
                }
            },
            dev: {
                lastStationId: '',
                lastNode: null,
                historyNodes: [],
                lastValues: [],
                nowValues: [],
                checkAll: false,
                doReturn: true,
                data: [],
                nzTreeClick: (e) => {
                    this.addData.dev.lastNode = e.node;
                    const hisNodes = this.addData.dev.historyNodes;
                    if (hisNodes.findIndex(el => el.key == e.node.key) == -1) {
                        this.addData.dev.historyNodes.push(e.node);
                    }
                    this.addData.dev.doReturn = false;
                },
                wrongSelect: false,
                onDevChange: (e) => {
                    if (this.addData.dev.doReturn) {
                        return;
                    }
                    let childKeys = [];
                    const wrongFunc = () => {
                        if (this.addData.dev.wrongSelect) {
                            setTimeout(() => {
                                this.addData.dev.doReturn = true;
                                this.addData.dev.nowValues = this.addData.dev.lastValues;
                                this.addData.dev.wrongSelect = false;
                            }, 300);
                        } else if (this.addData.dev.checkAll) {
                            this.addData.dev.doReturn = true;
                            this.addData.dev.nowValues = this.addData.dev.lastValues.concat(childKeys);
                            this.addData.dev.lastValues = this.addData.dev.nowValues;
                            this.addData.dev.checkAll = false;
                        } else {
                            this.addData.dev.lastValues = e;
                        }
                    };
                    if (e && e.length) {
                        // let nodes = this.treeSelect_add.selectedNodes;
                        if (this.addData.dev.lastNode.level == 0) {
                            this.message.create('error', '您选的是设备类型,请展开后选择设备');
                            this.addData.dev.wrongSelect = true;
                            wrongFunc();
                        } else if (this.addData.dev.lastNode.level == 1) {
                            this.addData.dev.checkAll = true;
                            this.modalService.confirm({
                                nzTitle: '操作确认',
                                nzContent: `您选的是设备类型,您需要 全选 该类型下的设备吗？（需要先展开该节点）`,
                                nzOkText: '确定',
                                nzCancelText: '取消',
                                nzOnOk: () => {
                                    const lastNode = this.addData.dev.lastNode;
                                    if (lastNode.isExpanded == false && lastNode.children && !lastNode.children.length) {
                                        this.message.warning(`请先展开该节点`);
                                        return;
                                    } else {
                                        childKeys = [];
                                        lastNode.children.forEach(childNode => {
                                            childKeys.push(childNode.key);
                                            const hisNodes = this.addData.dev.historyNodes;
                                            if (hisNodes.findIndex(el => el.key == childNode.key) == -1) {
                                                this.addData.dev.historyNodes.push(childNode);
                                            }
                                            // this.addData.dev.historyNodes.push(childNode);
                                        });
                                    }
                                    wrongFunc();
                                },
                                nzOnCancel: () => {
                                    this.addData.dev.wrongSelect = true;
                                    wrongFunc();
                                }
                            });
                        } else {
                            wrongFunc();
                        }
                    }

                }
            },
            traficImg: (e) => {
                if (e && e.type === 'success') {
                    const url = e.file.response.download;
                    this.formgroup_add.patchValue({
                        [this.ctrlNames_add.addrUrl]: url,
                    });
                }
            }

        };
    }

    initDetailData() {
        /**
         * 新增弹窗中的各控件需要的数据及逻辑
         */
        this.detailData = {
            station: {
                name: '',
                id: '',
            },
            dev: {

            },
        };
    }

    _addControls(group?, ctrlNames?) {
        if (!ctrlNames) {
            ctrlNames = this.ctrlNames;
        }
        if (!group) {
            group = this.formgroup_query;
        }
        const values = Object.values(ctrlNames);
        values.forEach(el => {
            group.addControl(el, new FormControl());
        });
    }

    stringEqual(obj1: object, obj2: object) {
        const str1 = JSON.stringify(obj1);
        const str2 = JSON.stringify(obj2);
        return str1 == str2;
    }


    /**
     *
            nId	作业门ID
            name	作业门名称
            dev	包含设备
            station	所属车站
            doorkey 钥匙所在地
            addrUrl	交通图链接地址
     */
    query(reset: boolean = false) { 
        if (reset == true || this.data.tablePagination.page == 0) {
            this.data.tablePagination.page = 1;
        }
        const vfv = this.formgroup_query.value;
        // let ctrlNames = this.data.ctrlNames;
        const param: any = {};
        param.nId = vfv[this.ctrlNames.nId] || '';
        param.name = vfv[this.ctrlNames.name] || '';
        param.dev = vfv[this.ctrlNames.dev] || '';
        param.station = vfv[this.ctrlNames.station] || '';

        param.page = this.data.tablePagination.page;
        param.limit = this.data.tablePagination.rows;

        this.zymgl_dispatcher(
            'zymgl_query', param, 'query', 'get'
        ).subscribe(res => {
            let _data;
            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            this.data.tableTotal = _data.count;
            _data.data.forEach(el => {
                if (el.station) {
                    el.stationTrans = this.translateStation2(el.station) || '';
                }
                if (el.dev) {
                    const decRes = this.decodeDevValues(el.dev);
                    const names = [];
                    decRes.forEach(data => {
                        names.push(data.name);
                    });
                    el.devName = names.join();
                    el.decRes = decRes;
                }
            });
            this.data.tableData = _data.data;

        });
    }

    isStationName(str) {
        return /[\u4e00-\u9fa5]+/.test(str);
    }



    nzPageIndexChange() {
        if (this.data.tablePagination.page == 0) {
            return;
        }
        this.query();
    }

    setPageSize() {

        this.query(true);

    }

    getObs(taskids) {
        const obs = [];
        taskids.forEach(el => {
            const ob = this.apiService.gjqdgl_dispatcher(
                'zymgl_sh', { taskId: el }, 'save', 'post'
            );
            obs.push(ob);
        });
        return obs;
    }


    showAddPanel() {
        this.addPanel.showAdd = true;
        this.formgroup_add.reset();
    }

    hideAddPanel() {
        this.addPanel.showAdd = false;
    }

    showEditPanel(row) {
        this.editPanel.showEdit = true;
        this.formgroup_edit.reset();
        this.editPanel.title = `修改作业门 ${row.name}[${row.nId}]`;
        this.editData.dev.historyNodes = [];
        this.editData.dev.lastValues = [];
        const v = {};
        for (const key in row) {
            if (row.hasOwnProperty(key) && this.ctrlNames_edit[key]) {
                const el = row[key];
                if (key == 'dev') {
                    const ids = [];
                    row.decRes.forEach(data => {
                        ids.push(data.id);
                    });
                    v[this.ctrlNames_edit[key]] = ids;
                    this.editData.dev.lastValues = ids;
                    // v[this.ctrlNames_edit[key]] = el.split(',');
                } else {
                    v[this.ctrlNames_edit[key]] = el;
                }
            }
        }
        this.editData.dev.station.id = row.station;
        this.editData.dev.station.name = row.stationTrans;
        // this.editData.dev.lastStationId = row.station;
        this.editData.row = row;

        this.devClick('edit', () => {
            this.formgroup_edit.patchValue(v);
        });

        const decRes = this.editData.row.decRes;
        decRes.forEach(el => {
            if (!el.typeId || el.typeId == 'undefined') {
                return;
            }
            this.editData.dev.historyNodes.push({
                key: el.id,
                title: el.name,
                parentNode: el.typeId,
            });
        });
    }

    hideEditPanel() {
        this.editPanel.showEdit = false;
    }

    getNodesFromHistory(optType, ids) {
        // const nodes = [];
        if (optType == 'add') {
            return this.addData.dev.historyNodes.filter(el => ids.includes(el.key));
        } else if (optType == 'edit') {
            return this.editData.dev.historyNodes.filter(el => ids.includes(el.key));
        }
    }

    /**
     * 保存之前对设备字段进行处理
     * 处理结果: [设备ID_设备名称_设备类型ID]或者[ID,ID2]
     * @param optType
     * @param arr
     */
    encodeDevValues(optType, arr) {
        const nodes = this.getNodesFromHistory(optType, arr);
        if (nodes.length !== arr.length) { 
            this.message.error('encodeDevValues错误,存在设备ID没有匹配到node的情况', { nzDuration: 1000 });
            return;
        } else {
            for (let i = 0; i < arr.length; i++) {
                const el = arr[i];
                const node = nodes[i];
                const pNode = node.parentNode;
                const pId = pNode.key || pNode;
                arr[i] = `${arr[i]}_${node.title}_${pId}`;
            }
        }
        return arr;
    }

    /**
     * 查询之后对设备字段进行解码
     * @param str
     */
    decodeDevValues(str) {
        const arr = str.split(','); // 设备ID_设备名称_设备类型ID
        const res = [];
        arr.forEach(el => {
            const _arr = el.split('_');
            const item = {
                id: _arr[0],
                name: _arr[1],
                typeId: _arr[2],
            };
            res.push(item);
        });
        return res;
    }



    addZym() {
        this.addPanel.loading = true;
        const fgv = this.formgroup_add.value;
        const param: any = {};
        // param.nId = fgv[this.ctrlNames.zymid] || '';
        param.name = fgv[this.ctrlNames_add.name] || ''; // 作业门名称
        const dev = fgv[this.ctrlNames_add.dev] || ''; // 包含设备
        // param.dev = dev.join() || '';// 包含设备
        param.dev = this.encodeDevValues('add', dev).join();
        param.station = fgv[this.ctrlNames_add.station] || ''; // 所属车站
        param.doorkey = fgv[this.ctrlNames_add.doorkey] || ''; // 钥匙所在地
        param.addrUrl = fgv[this.ctrlNames_add.addrUrl] || ''; // 交通图链接地址
        this.zymgl_dispatcher(
            'zymgl_add', param, 'add', 'post'
        ).subscribe(res => {
            this.addPanel.loading = false;
            let _data;
            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            if (_data.msg === 'Ok') {
                this.message.create('success', '新增成功');
                this.addPanel.showAdd = false;
            } else {
                this.message.create('error', '新增失败');
            }

            this.query(false);
        });
    }


    editZym() {
        const param: any = {};
        const fgv = this.formgroup_edit.value;
        param.nId = fgv[this.ctrlNames_edit.nId] || '';
        param.name = fgv[this.ctrlNames_edit.name] || ''; // 作业门名称
        const dev = fgv[this.ctrlNames_edit.dev] || ''; // 包含设备
        // param.dev = dev.join() || '';//包含设备
        if (dev.length) {
            if (dev[0].includes('_')) {
                param.dev = dev;
            } else {
                param.dev = this.encodeDevValues('edit', dev).join();
            }
        }
        const station = fgv[this.ctrlNames_edit.station] || ''; // 所属车站
        if (this.isStationName(station)) {
            param.station = this.editData.dev.station.id;
        } else {
            param.station = station;
        }

        param.doorkey = fgv[this.ctrlNames_edit.doorkey] || ''; // 钥匙所在地
        param.addrUrl = fgv[this.ctrlNames_edit.addrUrl] || ''; // 交通图链接地址
        this.zymgl_dispatcher(
            'zymgl_update', param, 'save', 'post'
        ).subscribe(res => {
            let _data;

            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }

            if (_data.msg === 'Ok') {
                this.message.create('success', '保存成功');
                this.editPanel.showEdit = false;
            } else {
                this.message.create('error', '保存失败');
            }

            this.query(false);
            this.pic.src = '';
        });
    }

    getDev(stationId, devType) {
        if (!stationId || !devType) {
            return;
        }
        return this.apiService.equipmentData(
            stationId, devType, '', ''
        );
        // .subscribe(res => {
        //     let _data;

        //     if (typeof res == 'string') {
        //         _data = JSON.parse(res);
        //     } else {
        //         _data = res;
        //     }

        // });
    }

    /**
     * 将设备类型的查询结果转化为zorro可以接受的结构
     * @param nodes
     */
    formatNodes(nodes) {
        if (!nodes || !nodes.length) {
            return;
        }
        nodes.forEach(node => {
            if (node.id) {
                node.key = node.id;
                if (node.text) {
                    node.title = node.text;
                }
                if (node.children && node.children.length) {
                    this.formatNodes(node.children);
                }
            }
        });
    }

    formatSynNodes(nodes) {
        if (!nodes || !nodes.length) {
            return;
        }
        nodes.forEach(node => {
            if (node.id) {
                node.key = node.id;
                if (node.text) {
                    node.title = node.text;
                }
                if (node.children && node.children.length) {
                    this.formatSynNodes(node.children);
                } else {
                    node.isLeaf = true;
                }
            }
        });
    }

    getDevType(stationId) {
        if (!stationId) {
            return;
        }
        return this.apiService.getAllTypesByStaId(
            stationId
        );
    }

    translateStation(id) {
        const stationData = this.queryData.station.data;
        if (stationData.length) {
            for (const item of stationData) {
                if (item.opValue == id) {
                    return item.opName;
                }
            }
        }
        return '';
    }

    translateStation2(id, nodes?) {
        if (!nodes) {
            nodes = this.queryData.station.data;
        }
        if (nodes.length) {
            for (const item of nodes) {
                if (item.children) {
                    const name = this.translateStation2(id, item.children);
                    if (name) {
                        return name;
                    }
                } else {
                    if (item.key == id) {
                        return item.title;
                    }
                }
            }
        }
        return '';
    }

    getStation(func) {

        this.apiService.getorgstatree().subscribe(res => {
            let _data;

            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }
            this.formatSynNodes(_data);
            this.queryData.station.data = _data;
            this.queryData.station.filterData = this.queryData.station.data;
            this.addData.station.data = _data;
            this.addData.station.filterData = this.queryData.station.data;
            this.editData.station.data = _data;
            this.editData.station.filterData = this.queryData.station.data;
            if (func) {
                func();
            }
        });

    }

    deleteZym(row) {
        const id = row.nId;
        if (!id) {
            return;
        }
        this.zymgl_dispatcher(
            'zymgl_del', { nId: id }, 'del', 'post'
        ).subscribe(res => {
            let _data;

            if (typeof res == 'string') {
                _data = JSON.parse(res);
            } else {
                _data = res;
            }

            if (_data.msg === 'Ok') {
                this.message.create('success', '删除成功');
            } else {
                this.message.create('error', '删除失败');
            }

            this.query(false);
        });
    }

    /*作业门管理*/
    zymgl_dispatcher(infoName: string, _param: any, flag: string, method: string) {
        let urls;
        if (flag == 'save') {// 修改
            urls = {
                'zymgl_update': '/workdoor/update', // 作业门修改
                'zymgl_updateAll': '/workdoor/updateBatch'// 作业门修改
            };
        } else if (flag == 'add') {// 新增
            urls = {
                'zymgl_add': '/workdoor/add', // 新增单个
                'zymgl_addAll': '/workdoor/addBatch'// 新增多个
            };
        } else if (flag == 'del') {// 删除
            urls = {
                'zymgl_del': '/workdoor/delete', // 删除
                'zymgl_delAll': '/workdoor/deleteBatch'// 删除
            };
            if (_param.nId) {
                return this.build_postInfo({}, urls[infoName] + '/' + _param.nId);
            }
        } else {// 查询
            urls = {
                'zymgl_query': '/workdoor/query'// 查询

            };
        }
        if (method == 'get') {
            return this.build_getInfo(_param, urls[infoName]);
        } else {
            return this.build_postInfo(_param, urls[infoName]);
        }
    }

    build_postInfo(_param: object, _url: string) {
        if (!_url) {
            return;
        }
        const url = environment.project + _url;
        const params = JSON.stringify(_param);
        return this.http.post(url, JSON.parse(params));
    }

    build_getInfo(_param: object, _url: string) {
        if (!_url) {
            return;
        }
        const url = environment.project + _url;
        return this.http.get(url, _param);
    }

    /**
     * 车站选中事件
     */
    stationSelect(optType, station) {
        if (optType == 'edit') {
            this.editData.dev.station.id = station.opValue;
            this.editData.dev.station.name = station.opName;
        }
    }

    onChange_cz(type, value) {

        switch (type) {
            case 'query':
                if (this.queryData.station.data.length) {
                    this.queryData.station.filterData = this.queryData.station.data.filter(el => el.opName.includes(value));
                    if (!value) {
                        this.queryData.station.filterData = this.queryData.station.data;
                        // this.queryData.dev.nowValues = [];
                    }
                }
                break;
            case 'add':
                if (this.addData.station.data.length) {
                    this.addData.station.filterData = this.addData.station.data.filter(el => el.opName.includes(value));
                    if (!value) {
                        this.addData.station.filterData = this.addData.station.data;
                    }
                    // this.addData.dev.nowValues = [];
                }
                break;
            case 'edit':
                if (this.editData.station.data.length) {
                    this.editData.station.filterData = this.editData.station.data.filter(el => {
                        return el.opName.includes(value) || el.opValue == value;
                    });
                    if (!value) {
                        this.editData.station.filterData = this.editData.station.data;
                    }
                    // this.editData.dev.nowValues = [];
                }
                break;
        }
    }

    // onChange_cz_add(value) {
    //     if (this.addData.station.data.length) {
    //         this.addData.station.filterData = this.addData.station.data.filter(el => el.opName.includes(value));
    //     }
    // }

    // onChange_cz_edit(value) {
    //     if (this.editData.station.data.length) {
    //         this.editData.station.filterData = this.editData.station.data.filter(el => el.opName.includes(value));
    //     }
    // }

    /**
     * 设备树节点展开事件
     * @param type
     * @param e
     */
    onDevExpand(type, e) {
        if (!type) {
            return;
        }
        let lastStationId;
        if (type == 'query') {
            lastStationId = this.queryData.dev.lastStationId;
        } else if (type == 'add') {
            lastStationId = this.addData.dev.lastStationId;
        } else if (type == 'edit') {
            lastStationId = this.editData.dev.lastStationId;
        }
        const node = e.node;
        if (node && !node.getChildren().length && node.isExpanded) {
            node.isLoading = true;
            this.getDev(lastStationId, node.key)
                .subscribe(res => {
                    node.isLoading = false;
                    let _data;
                    if (typeof res == 'string') {
                        _data = JSON.parse(res);
                    } else {
                        _data = res;
                    }
                    if (_data.data) {
                        const data = _data.data;
                        if (data.pageList.length) {
                            const devNodes = [];
                            data.pageList.forEach(el => {
                                devNodes.push({
                                    // id: el.opValue,
                                    key: el.opValue,
                                    title: el.opName,
                                    isLeaf: true,
                                });
                            });
                            node.addChildren(devNodes);
                        }
                    }
                });
            // this.loadNode().then(data => {
            //     node.addChildren(data);
            // });
        }
    }

    /**
     * 设备输入框点击事件，包含查询栏，新增弹窗和修改弹窗中的设备
     * @param type query/add/edit
     */
    devClick(type, _func?) {
        let stationId;
        let doTheQuery = false; // 是否需要执行查询，逻辑：如果是同一ID，表面已经查询过一次，则不需再次查询
        let func;
        if (type == 'query') {
            stationId = this.formgroup_query.value[this.ctrlNames.station];
            if (this.queryData.dev.lastStationId != stationId) {
                doTheQuery = true;
                func = _data => {
                    this.queryData.dev.data = _data;
                    this.queryData.dev.lastStationId = stationId;
                };
            }
        } else if (type == 'add') {
            stationId = this.formgroup_add.value[this.ctrlNames_add.station];
            if (this.addData.dev.lastStationId != stationId) {
                doTheQuery = true;
                func = _data => {
                    this.addData.dev.data = _data;
                    this.addData.dev.lastStationId = stationId;
                };
            }
        } else if (type == 'edit') {
            stationId = this.editData.dev.station.id;
            // if (true) {
            if (this.editData.dev.lastStationId != stationId) {
                // doTheQuery = true;
                const decode = this.editData.row.decRes;
                const expandNodeKeys = new Set();

                decode.forEach(el => {
                    if (el.typeId) {
                        expandNodeKeys.add(el.typeId);
                    }
                });
                this.unionTreeNodes(stationId, Array.from(expandNodeKeys), _func);
            } else {
                if (_func) {
                    _func();
                }
            }
        }
        if (stationId) {
            if (doTheQuery) {
                this.getDevType(stationId).subscribe(res => {
                    let _data;
                    if (typeof res == 'string') {
                        _data = JSON.parse(res);
                    } else {
                        _data = res;
                    }
                    this.formatNodes(_data);
                    func(_data);
                });
            }
        } else {
            this.message.create('error', '请先选择车站');

        }
    }

    getNodes(keys, nodes) {
        // nodes.forEach(node => {
        //     if (node.key==key) {

        //     }
        // });
        // let _nodes = nodes.filter(node => keys.includes(node.key))
        // if (nodes.length>0) {
        //     return nodes;
        // } else {
        //     this.getNodes(keys)
        // }
        let res = [];
        for (const item of nodes) {
            if (keys.includes(item.key)) {
                res.push(item);
            } else {
                if (item.children && item.children.length) {
                    const _nodes = this.getNodes(keys, item.children);
                    if (_nodes && _nodes.length) {
                        res = res.concat(_nodes);
                    }
                }
            }
        }
        return res;
    }

    unionTreeNodes(stationId, devTypeIds, func?) {
        const devTypeInfoOb = this.getDevType(stationId);
        const devObs = [];
        devTypeIds.forEach(devTypeId => {
            const devTypeOb = this.apiService.equipmentData(
                stationId, devTypeId, '', ''
            );
            devObs.push(devTypeOb);
        });
        const observables = [devTypeInfoOb, ...devObs];
        forkJoin(observables).subscribe(resArr => {
            let devTypeNode; let pNodes;
            this.editData.dev.lastStationId = stationId;
            for (let i = 0; i < resArr.length; i++) {
                const res = resArr[i];
                let _data;
                if (typeof res == 'string') {
                    _data = JSON.parse(res);
                } else {
                    _data = res;
                }
                if (i === 0) {
                    this.formatNodes(_data);
                    devTypeNode = _data;
                    pNodes = this.getNodes(devTypeIds, devTypeNode);
                    devTypeNode.forEach(node => {
                        node.disableCheckbox = true;
                    });
                } else {
                    if (_data.data) {
                        const data = _data.data;
                        if (data.pageList.length) {
                            const devNodes = [];
                            data.pageList.forEach(el => {
                                devNodes.push({
                                    // id: el.opValue,
                                    key: el.opValue,
                                    title: el.opName,
                                    isLeaf: true,
                                });
                            });
                            // let pnode = pNodes.filter(pNode => pNode.key == devTypeIds[i - 1]);
                            pNodes.forEach(pNode => {
                                if (pNode.key == devTypeIds[i - 1]) {
                                    pNode.children = devNodes;
                                }
                            });
                            // important
                            // 接下来在此处把设备节点存入 historynode
                        }
                    }
                }
            }
            this.editData.dev.data = devTypeNode;
            if (func) {
                func();
            }
        });

    }

    showDetail(row) {
        this.detailPanel.showdetail = true;
        this.formgroup_detail.reset();
        this.detailPanel.title = `查看作业门 ${row.name}[${row.nId}]`;
        if (row.station) {
            row.stationTrans = this.translateStation2(row.station) || '';
        }
        if (row.dev) {
            const decRes = this.decodeDevValues(row.dev);
            const names = [];
            decRes.forEach(data => {
                names.push(data.name);
            });
            row.devName = names.join();
            row.decRes = decRes;
        }
        const v = {};
        for (const key in row) {
            if (row.hasOwnProperty(key) && this.ctrlNames_detail[key]) {
                const el = row[key];
                if (key == 'dev') {
                    // const ids = [];
                    // row.decRes.forEach(el => {
                    //     ids.push(el.id);
                    // });
                    v[this.ctrlNames_detail[key]] = row.devName;
                    // v[this.ctrlNames_detail[key]] = el.split(',');
                } else {
                    v[this.ctrlNames_detail[key]] = el;
                }
            }
        }
        this.formgroup_detail.patchValue(v);
        this.pic.setUrl(row);
    }

    hideDetail() {
        this.detailPanel.showdetail = false;
    }
}
